/**
 * 映射配置 数据库表拖动
 */
let queryTableUrl = '/update/queryTable' //查询表
let queryFileUrl = '/update/queryFile'   //查询字段
let queryWhereUrl = '/update/queryWhere' //查询字典
let addMapperUrl = '/mapper/addMapper'                //增加映射配置
let updateMapperUrl = '/mapper/updateMapper'          //修改映射配置
let updateMapperByIdUrl = '/mapper/updateMapperById'  //详情
class Drag {
    constructor(options = {}) {
        this.options = options;
        this.$container = $(this.options.container_selector);
        this.$treeContainer = $('<div class="hide tree"></div>');
        this.$relationContainer = $('<div class="hide relation"><div class="_title">关联关系</div><div class="content"></div></div>');
        this.$list = $(this.options.list_selector);
        this.$promptText = $('<div class="prompt-text"><lable><i class=""></i>请将左侧的表拖入工作区</lable></div>');
        this.press = false;
        this.dragObj = {};
        this.data = { "name": "松表名(医疗信息)", "tname": "松表名", "tid": 81, "pid": -1, "id": 1, "children": [{ "name": "Kb01(TEST)", "tid": 155, "tname": "Kb01", "pid": 1, "id": 2, "fieldRelation": { "rtype": "left", "left-field": ["7", "8"], "right-field": ["103", "103"] } }] };
        this.data = {};
        this.index = 0;
        this.dragType = '';
        this.containerActive = false;
        //鼠标按下位置
        this.mousedownPos = {};
        //缓存表的字段
        this.fieldMap = {};
        //选中的id进行编辑或者添加字段关系
        this.selectedId = -1;

        this.tempData = null;

        this.eventsFlag = false;
    }

    init() {
        this.$container.append(this.$promptText);
        this.$container.append(this.$treeContainer).append(this.$relationContainer)
        this.$relationContainer.niceScroll($.po('niceScroll'));
        this.niceScroll = this.$treeContainer.niceScroll($.po('niceScroll', { railpadding: { bottom: -1, right: -1 } }));
        this.niceScroll.rail.css({ zIndex: '2' })
        this.niceScroll.railh.css({ zIndex: '2' })
        if (mappedAddView.type != 'edit') {
            // this.events();
        } else {
            this.$promptText.addClass('hide')
            this.$relationContainer.removeClass('hide')
        }
        this.resetPageElement(2);
    }

    /**
     * 统一事件处理
     */
    events() {
        let self = this;
        if (this.eventsFlag) return false;
        this.eventsFlag = true;
        //左侧列表的 鼠标按下事件
        this.$list.on('mousedown.wddrag','li', e => {
                this.dragType = 'list';
                // this.press = true;
                this.mousedownPos = {
                    x: e.clientX,
                    y: e.clientY
                }
                this.dragObj = {
                    $element: $(e.currentTarget),
                    startX: e.clientX,
                    startY: e.clientY
                };
            });
        //右侧区域内    dragable 鼠标按下事件
        this.$container.on('mousedown.wddrag', '.box .dragable', e => {
            if ($(e.target).parent().hasClass('edit-btn') || $(e.target).parent().hasClass('del-btn')) {
                //在编辑删除按钮上按下并拖动需要阻止冒泡事件,并返回
                e.stopPropagation();
                return false;
            }
            this.dragType = 'detail';
            this.mousedownPos = {
                x: e.clientX,
                y: e.clientY
            }
            this.dragObj = {
                $element: $(e.target).parents('.box:eq(0)'),
                startX: e.clientX,
                startY: e.clientY
            };
            //获取当前拖动的对象,有可能是个对象数
            this.dragObj.childObj = this.findDataById(this.dragObj.$element.data('id'));
            console.log(this.dragObj.childObj)
        }).on('click.wddrag', '.del-btn', (e) => {
            if ($(e.currentTarget).parents('.box:eq(0)').find('.box').length) {
                alertify.error('有子级无法删除')
            } else {
                self.removeDataById($(e.currentTarget).parents('.box:eq(0)').data('id'));
                self.dataToHtml();
                alertify.success('删除成功');
                this.resetPageElement(2)
            }

        }).on('click.wddrag', '.edit-btn', (e) => {
            self.editElement = e;
            self.selectedId = $(e.currentTarget).parents('.box:eq(0)').data('id');

            let fieldRelation = self.findDataById(self.selectedId).fieldRelation;//映射关系
            if (fieldRelation) {
                $('#source_table_form .btn-group .active').removeClass('active');
                $('#source_table_form .btn-group [name=rtype][value=' + fieldRelation.rtype + ']').parent().addClass('active');
            } else {
                $('#source_table_form .btn-group .active').removeClass('active');
                $('#source_table_form .btn-group [name=rtype][value=left]').parent().addClass('active');
            }
            //弹出框 
            mappedAddView.plugins.source_table_container.show();
            self.btnGroup((fieldRelation && fieldRelation.rtype) || 'left', fieldRelation || {});
        });

        $(document)
            //全局鼠标移动事件    
            .unbind('mousemove.wddrag').bind('mousemove.wddrag', e => {
                if (this.dragObj && this.dragObj.$element && this.dragObj.$element.parents('form').length) {
                    return false;
                }
                if (this.mousedownPos.x && this.mousedownPos.y && (e.clientX != this.mousedownPos.x || e.clientY != this.mousedownPos.y)) {
                    this.press = true;
                } else {
                    this.press = false;
                }


                if (this.press && this.$container.find('[data-tid=' + this.dragObj.$element.data('tid') + ']').length == 0) {
                    this.status(e);
                    this.move(e)
                } else {
                    this.press = false;
                }
            })
            //全局鼠标松开事件    
            .unbind('mouseup.wddrag').bind('mouseup.wddrag', e => {
                this.mousedownPos = {};
                if (this.press) {
                    this.press = false;
                    this.updataView();
                    if (this.dragObj.$tempDragContainer) {
                        this.dragObj.$tempDragContainer.remove();
                    }
                }
                this.$container.removeClass('active')
            }).on('click', '#source_table_container [data-toggle="buttons"] .btn', e => {
                self.btnGroup($(e.currentTarget).find('input').val() || 'left');
            })

        $('#select-target-table').unbind('change.wddrag').bind('change.wddrag', (e) => {
            if (e.target.value) {
                self.activatePageElement(3);
            } else {
                self.resetPageElement(3);
            }
        })
    }

    queryField(data, callback) {
        let self = this;
        data.validFlag = 0;
        // if (data.tid != this.data.tid) {
        //     data.validFlag = 0;
        // } else {
        //     data.validFlag = 1;
        // }
        if (!this.fieldMap['_' + data.tid]) {
            wdAjax.post({
                url: queryFileUrl,
                data,
                success(_data) {
                    self.fieldMap['_' + data.tid] = _data;
                    if (callback)
                        callback(self.fieldMap['_' + data.tid])
                }
            })
        } else {
            callback(this.fieldMap['_' + data.tid])
        }

    }
    /**
     * 算法
     * 当从左侧拖动一个块到右侧，激活最近的一个
     */
    optimal(type, x, y) {
        if (type) {
            this.$container.find('.dragable.active').removeClass('active');
            if (this.$container.find('.dragable').length == 1) {
                this.$container.find('.dragable').addClass('active');
            } else if (this.$container.find('.dragable').length > 1) {
                //两个点最近距离
                let dragableArr = this.$container.find('.dragable');
                let minDistance = 9999999;
                let minDistanceIndex = -1;
                for (let i = 0; i < dragableArr.length; i++) {
                    let y2 = $(dragableArr[i]).offset().top + 17;
                    let x2 = $(dragableArr[i]).offset().left + 100;
                    let distance = Math.sqrt(Math.pow(x2 - x, 2) + Math.pow(y2 - y, 2));
                    if (minDistance > distance) {
                        minDistance = distance;
                        minDistanceIndex = i;
                    }
                }
                $(dragableArr[minDistanceIndex]).addClass('active');
            }
        } else {
            //清除所有选中状态
            this.$container.find('.dragable.active').removeClass('active')
        }
    }
    /**
     * 更新视图
     */
    updataView() {
        if (this.containerActive) {
            if (!this.data.name) {
                //第一张表
                this.data.name = this.dragObj.$tempDragContainer.find('[data-tname]').data('tname');
                this.data.tname = this.dragObj.$tempDragContainer.find('[data-tname]').data('tname');
                this.data.tid = this.dragObj.$tempDragContainer.find('[data-tid]').data('tid');
                this.data.talias = this.dragObj.$tempDragContainer.find('[data-talias]').data('talias');
                this.data.tnandc = this.dragObj.$tempDragContainer.find('[data-tnandc]').data('tnandc');
                this.data.tcomments = this.dragObj.$tempDragContainer.find('[data-tcomments]').data('tcomments');
                this.data.pid = -1;
            } else {
                //更新位置之前需要先检查拖动的位置是否合理，不能不父级移动到自己的子级下面
                if (!this.dragObj.$element.find('.active').length) {
                    //添加到active对象的下面
                    let targetObj = this.findDataById(this.$container.find('.active').parent().data('id'));
                    if (!targetObj.children) {
                        targetObj.children = [];
                    }
                    if (this.dragType == 'list') {
                        targetObj.children.push({
                            name: this.dragObj.$tempDragContainer.find('[data-tname]').data('tname'),
                            tid: this.dragObj.$tempDragContainer.find('[data-tid]').data('tid'),
                            tname: this.dragObj.$tempDragContainer.find('[data-tname]').data('tname'),
                            alias: this.dragObj.$tempDragContainer.find('[data-talias]').data('talias'),
                            pid: this.$container.find('.active').parents('.box:eq(0)').data('id'),
                            talias: this.dragObj.$tempDragContainer.find('[data-talias]').data('talias'),
                            tcomments: this.dragObj.$tempDragContainer.find('[data-tcomments]').data('tcomments'),
                            tnandc: this.dragObj.$tempDragContainer.find('[data-tnandc]').data('tnandc')
                        })
                    } else {
                        //添加到新位置
                        let newObj = JSON.parse(JSON.stringify(this.dragObj.childObj));
                        if (targetObj.id != newObj.id) {
                            newObj.id = null;
                            targetObj.children.push(newObj)
                            //拖动完毕后需要删除之前的位置
                            this.removeDataById(this.dragObj.childObj.id);
                        }
                    }
                }
            }
        }
        //更新promptText
        if (this.data.name) {
            this.$promptText.addClass('hide')
            this.$treeContainer.removeClass('hide')
            this.$relationContainer.removeClass('hide')
            this.dataToHtml();
        } else {
            this.$promptText.removeClass('hide')
            this.$treeContainer.addClass('hide')
            this.$relationContainer.addClass('hide')
        }
    }

    /**
     * 根据id递归查找
     */
    findDataById(id) {
        let result = {};
        function find(data, ) {
            if (data.id == id) {
                result = data;
                return true;
            }
            if (data.children && data.children.length) {
                for (let i = 0; i < data.children.length; i++) {
                    if (find(data.children[i])) {
                        return true;
                    }
                }
            }

        }
        find(this.data);
        return result;
    }

    //获取已配置表源关系所有表的字段
    getSelectedTableField() {
        let fieldMap = {};
        this.$container.find('.box').map((i, table) => {
            let tname = $(table).data('tname');
            let tid = $(table).data('tid');
            fieldMap['_' + tid] = this.fieldMap['_' + tid];
        })
        return fieldMap;
    }

    jsonToArr() {
        let arr = [];
        function find(data) {
            arr.push({
                name: data.tname,
                pid: data.pid,
                tid: data.tid,
                id: data.id,
                tname: data.tname,
                fieldRelation: data.fieldRelation,
                talias: data.talias,
                alias: data.talias,
                tcomments: data.tcomments,
                tnandc: data.tnandc,


            })
            if (data.children && data.children.length) {
                for (let i = 0; i < data.children.length; i++) {
                    if (find(data.children[i])) {
                        return true;
                    }
                }
            }
        }
        find(this.data);
        return arr;

    }
    /**
     * 根据id删除对象
     */
    removeDataById(id) {
        function find(data) {
            if (data.id == id) {
                return true;
            }
            if (data.children && data.children.length) {
                for (let i = 0; i < data.children.length; i++) {
                    if (data.children && find(data.children[i])) {
                        data.children.splice(i, 1)
                        if (data.children.length == 0) {
                            delete (data.children)
                        }
                        break;
                    }
                }
            }
        }
        find(this.data);
        if (id == 1) {
            this.data = {};
        }
    }

    /**
     * 把data转为html放在treeContainer
     */
    dataToHtml() {
        let self = this;
        this.$treeContainer.html('');
        this.index = 0;
        function parse(arr, parentid) {
            arr.map(item => {
                self.index++;
                let name = item['name'];
                let id = self.index;
                item.id = id;
                let children = item['children'] || [];
                let $box = $(`<div class="box" data-id="${id}" data-tname="${item.tname}" data-tid="${item.tid}" id="box_${id}">
                                <div class="dragable children_${children.length} pr">
                                    <div class="info omit">${item.talias}</div>
                                    <div class="del-btn"><i class="iconfont icon-shachu-xue"></i></div>
                                    <div class="edit-btn pa" data-type="add or edit">
                                        <i class="edit-icon ${item.fieldRelation ? '' : 'hide'} iconfont icon-bianji1" title="编辑" ></i>
                                        <i class="add-icon ${item.fieldRelation ? 'hide' : ''} iconfont icon-jia1 title="添加"></i>
                                    </div>
                                </div>
                                <div class="wrap wrap_${id}"></div>
                            </div>`);
                if (item.name) {
                    if (parentid == -1) {
                        self.$treeContainer.append($box);
                    } else {
                        self.$treeContainer.find(`.wrap_${parentid}`).append($box);
                    }
                }

                if (children.length) {
                    parse(children, id)
                }

            })

        }
        if (this.data.name) {
            parse([this.data], -1);
        } else {
            self.$treeContainer.html('')
        }
        this.updataStyle();
        self.index++;
        this.sqlStr();
        //判断第一步是否完成
        if (this.getData() === false) {
            this.resetPageElement(2);
        } else {
            this.activatePageElement(2);
        }
    }

    /**
     * 更新container的状态
     * @param {*} e 
     */
    status(e) {
        let x = e.clientX;
        let y = e.clientY;
        if (this.press) {
            var y1 = this.$container.offset().top;
            var y2 = y1 + this.$container.height();
            var x1 = this.$container.offset().left;
            var x2 = x1 + this.$container.width();
            if (x < x1 - 10 || x > x2 + 20 || y < y1 - 10 || y > y2 + 20) {
                this.containerActive = false;
                this.$container.removeClass('active')
                this.optimal(false, x, y);
            } else {
                this.containerActive = true;
                this.$container.addClass('active')
                this.optimal(true, x, y)
            };
        }
    }

    /**
     * 移动鼠标按下的元素
     * @param {*} e 
     */
    move(e) {
        let x = e.clientX;
        let y = e.clientY;
        if (!this.dragObj.$tempDragContainer && (this.dragObj.startX != x || this.dragObj.startY != y)) {
            this.dragObj.$tempDragContainer = $('<div class="temp_drag_container"></div>');
            if (this.dragType == 'detail') {
                this.dragObj.$tempDragContainer.append('<div class="drag-container"><div class="tree"></div></div>').addClass('temp-drag-tree-container')
                this.dragObj.$tempDragContainer.find('.tree').html($('<div>').append(this.dragObj.$element.clone().unbind('mousedown.wddrag')).html())
            } else {
                this.dragObj.$tempDragContainer.html($('<div>').append(this.dragObj.$element.clone().unbind('mousedown.wddrag')).html())
            }

            $('body').append(this.dragObj.$tempDragContainer);
        }
        if (this.dragObj.$tempDragContainer) {
            this.dragObj.$tempDragContainer.css({
                top: y - 17,
                left: x - 100
            })
        }

    }

    /**
     * 修正style
     */
    updataStyle() {
        setTimeout(() => {
            $('.drag-style').remove();
            let styleStr = '';
            $('.dragable').map((i, dragable) => {
                let $dragable = $(dragable);
                let parentid = $dragable.parent().attr('id');
                let $lastChildren = $dragable.next().children('.box:last');
                let height = 0;
                if ($lastChildren.length) {
                    height = ($lastChildren.offset().top + 17) - ($dragable.offset().top + 34) - 9;
                    if (height < 0) height = 0;
                }
                styleStr += `
            .drag-container #${parentid} .dragable:before{
                height:${height}px;   
            }`
            })
            $('body').append(`<style class="drag-style">${styleStr}</style>`)
        })
    }

    dataToParams() {
        let _arr = [];
        let self = this;
        let result = {};
        let str = '';
        function find(data, ) {
            if (data.fieldRelation) {
                const leftTable = self.findDataById(data.pid);
                const rightTable = data;
                str += `${leftTable.tname} ${data.fieldRelation.rtype == 'left' ? 'LEFT' : 'RIGHT'} JOIN ${rightTable.tname} ON `

                let columnlist = [];
                data.fieldRelation['left-field'].map((val, index) => {
                    //根据 colId 获取对应 colname  LEFT
                    let leftColname = '';
                    for (let i = 0; i < self.fieldMap['_' + leftTable.tid].length; i++) {
                        if (self.fieldMap['_' + leftTable.tid][i].colId == val) {
                            leftColname = self.fieldMap['_' + leftTable.tid][i].colName
                            break;
                        }
                    }
                    //根据 colId 获取对应 colname  RIGHT
                    let rightColname = '';
                    for (let i = 0; i < self.fieldMap['_' + rightTable.tid].length; i++) {
                        let colId = data.fieldRelation['right-field'][index];
                        if (self.fieldMap['_' + rightTable.tid][i].colId == colId) {
                            rightColname = self.fieldMap['_' + rightTable.tid][i].colName
                            break;
                        }
                    }
                    if (rightTable.fieldRelation.rtype == 'left') {
                        columnlist.push({
                            from: rightColname,
                            to: leftColname
                        })
                    } else {
                        columnlist.push({
                            from: leftColname,
                            to: rightColname
                        })
                    }

                })

                _arr.push({
                    columnlist,
                    "left": leftTable.tname,
                    "right": rightTable.tname,
                    "type": rightTable.fieldRelation.rtype
                })
            }
            if (data.children && data.children.length) {
                for (let i = 0; i < data.children.length; i++) {
                    if (find(data.children[i])) {
                        return true;
                    }
                }
            }

        }
        find(this.data);
        return _arr;
    }

    getData(type, flag) {
        if (flag || this.$container.find('.add-icon:not(".hide")').length <= 1) {
            if (type == 'array') {
                return this.jsonToArr()
            } else {
                if (this.data.name) {
                    return this.data;
                } else {
                    return false;
                }

            }
        } else {
            return false;
        }
    }
    /**
     * 
     * @param {*} type 
     * @param {*} fieldRelation 两表字段之间的关联关系
     */
    btnGroup(type = 'left', fieldRelation = {}) {
        let self = this;
        //添加关系弹出框 
        let parenttid = $(self.editElement.target).parents('.box:eq(1)').data('tid')
        let tid = $(self.editElement.target).parents('.box:eq(0)').data('tid');

        let tName = self.findDataById(self.selectedId).tname
        let parentName = self.findDataById(self.findDataById(self.selectedId).pid).tname;
        if (mappedAddView.plugins['source_table_content'].$table.find('.selectpicker').data() && mappedAddView.plugins['source_table_content'].$table.find('.selectpicker').data().selectpicker) {
            mappedAddView.plugins['source_table_content'].$table.find('.selectpicker').data().selectpicker.destroy();
        }

        $('#source_table_content thead:eq(0) th:eq(0)').text(parentName)
        $('#source_table_content thead:eq(0) th:eq(2)').text(tName)
        $('#source_table_content').parents('.dataTables_scroll').find('thead:eq(0) th:eq(0)').text(parentName);
        $('#source_table_content').parents('.dataTables_scroll').find('thead:eq(0) th:eq(2)').text(tName);
        self.queryField({ tid: tid }, data => {
            self.queryField({ tid: parenttid }, data => {
                //设置表格数据
                let tableData = [];
                // let type = $('[data-toggle="buttons"] .active input').val();
                if (type == 'left') {
                    //左关联
                    self.fieldMap['_' + parenttid].map((item, index) => {
                        let data = {
                            mname: item,
                            '=': '=',
                            tto: self.fieldMap['_' + tid]
                        };
                        if (fieldRelation && fieldRelation.rtype && fieldRelation.rtype == 'left') {
                            for (let i = 0; i < data.tto.length; i++) {
                                if (data.tto[i].colId == fieldRelation['right-field'][index]) {
                                    data.tto[i].selected = true;
                                } else {
                                    data.tto[i].selected = false;
                                }
                            }
                        }
                        if (item.pkFlag == 1) {
                            tableData.push(JSON.parse(JSON.stringify(data)))
                        }
                    })
                } else {
                    self.fieldMap['_' + tid].map((item, index) => {
                        let data = {
                            mname: self.fieldMap['_' + parenttid],
                            '=': '=',
                            tto: item
                        };
                        if (fieldRelation && fieldRelation.rtype && fieldRelation.rtype == 'right') {
                            for (let i = 0; i < data.mname.length; i++) {
                                if (data.mname[i].colId == fieldRelation['left-field'][index]) {
                                    data.mname[i].selected = true;
                                } else {
                                    data.mname[i].selected = false;
                                }
                            }
                        }
                        if (item.pkFlag == 1) {
                            tableData.push(JSON.parse(JSON.stringify(data)))
                        }
                    })
                }
                mappedAddView.plugins['source_table_content'].options.data = tableData;
                if (mappedAddView.plugins['source_table_content']._table) {
                    mappedAddView.plugins['source_table_content'].api.draw();
                    mappedAddView.plugins['source_table_content'].$table.find('.selectpicker').selectpicker($.po('selectpicker', { container: 'body' }));
                    mappedAddView.plugins.source_table_form.formValidation.destroy()
                    mappedAddView.plugins.source_table_form.init()
                }
            })
        })
    }
    /**
     * 更新字段关系
     */
    updataFieldRelation(data) {
        if (typeof data['left-field'] == 'string') {
            data['left-field'] = [data['left-field']];
        }
        if (typeof data['right-field'] == 'string') {
            data['right-field'] = [data['right-field']];
        }
        let selectedData = this.findDataById(this.selectedId)
        selectedData.fieldRelation = data;
        this.dataToHtml();
    }

    getAllField(cb) {
        let tableArr = [];
        $('.drag-list li').map((i, item) => {
            tableArr.push({
                tid: $(item).data('tid')
            })
        })
        let self = this;
        let index = 0;
        function get() {
            if (index >= tableArr.length) {
                cb.call(self);
                return false;
            }
            let tid = tableArr[index].tid;
            index++;
            self.queryField({ tid }, get)
        }
        get();
    }
    /**
     * 
     */
    sqlStr() {
        // KC24  LEFT  JION  KC21  ON   KC24.AAA027=KC21.AAA038  
        // LEFT  JION  KA02  ON   KA02.AAA027=KC24.AAA038  
        // LEFT  JION  AA10_TABLE ON  AA10_TABLE.AAA027=KA02.AAA028
        this.getAllField(() => {
            let self = this;
            let result = {};
            let str = '';
            let gindex = 0;
            let sqlArr = [];
            function find(data, ) {
                if (data.fieldRelation) {
                    const leftTable = self.findDataById(data.pid);
                    const rightTable = data;
                    str = `${leftTable.tname} ${data.fieldRelation.rtype == 'left' ? 'LEFT' : 'RIGHT'} JOIN ${rightTable.tname} ON `
                    if (typeof data.fieldRelation['left-field'] == 'string') {
                        data.fieldRelation['left-field'] = [data.fieldRelation['left-field']]
                    }
                    data.fieldRelation['left-field'].map((val, index) => {
                        //根据 colId 获取对应 colname  LEFT
                        let leftColname = '';
                        for (let i = 0; i < self.fieldMap['_' + leftTable.tid].length; i++) {
                            if (self.fieldMap['_' + leftTable.tid][i].colId == val) {
                                leftColname = self.fieldMap['_' + leftTable.tid][i].colName
                                break;
                            }
                        }
                        //根据 colId 获取对应 colname  RIGHT
                        let rightColname = '';
                        for (let i = 0; i < self.fieldMap['_' + rightTable.tid].length; i++) {
                            let colId = data.fieldRelation['right-field'][index];
                            if (self.fieldMap['_' + rightTable.tid][i].colId == colId) {
                                rightColname = self.fieldMap['_' + rightTable.tid][i].colName
                                break;
                            }
                        }
                        str += `${leftTable.tname}.${leftColname}=${rightTable.tname}.${rightColname} `
                    })
                    if (gindex == 0) {
                        sqlArr.push(`<p>${str}</p>`)
                        gindex = 1;
                    } else {
                        sqlArr.push(`<p>${str.replace(/.*?\s/, '')}</p>`)
                    }

                }
                if (data.children && data.children.length) {
                    for (let i = 0; i < data.children.length; i++) {
                        if (find(data.children[i])) {
                            return true;
                        }
                    }
                }

            }
            find(this.data);
            // console.log(str)
            this.$container.find('.relation .content').html(sqlArr.toString().replace(/\,/g, ''))
            return str;
        })
    }

    test() {
        $('.prompt-text').remove()
        $('.hide.tree').removeClass('hide');
        this.$relationContainer.removeClass('hide')
        this.dataToHtml()

        let boxs = $('#box_3').parents('.box');
        let tempData = [this.data];
        for (let i = boxs.length - 1; i >= 0; i--) {
            tempData = tempData[boxs.eq(i).index()].children

        }
        console.log(tempData)
    }

    queryTableByName(tableName) {
        for (let i = 0; i < this.tableList.length; i++) {
            if (this.tableList[i].name == tableName) {
                return this.tableList[i];
                break;
            }
        }
        return null;
    }

    editUpdataData() {
        // tempData
        // tableList
        let sqlStr = '';
        let self = this;
        if (this.tempData && this.tempData.length > 0) {
            this.tempData.map((item, index) => {
                if (index == 0) {
                    let leftTable = self.queryTableByName(item.left);
                    self.$treeContainer.append(`<div class="box" id="box_${leftTable.id}" data-name="${leftTable.name}">
                                                <div class="dragable pr">
                                                    <div class="info omit">${leftTable.talias}</div>
                                                </div>
                                                <div class="wrap"></div>
                                            </div>`);
                    let rightTable = self.queryTableByName(item.right);
                    self.$treeContainer.find('.box:eq(0) .wrap:eq(0)').append(`
                                            <div  id="box_${rightTable.id}" class="box" data-name="${rightTable.name}">
                                                        <div class="dragable pr">
                                                            <div class="info omit">${rightTable.talias}</div>
                                                        </div>
                                                        <div class="wrap"></div>
                                                    </div>`)
                    sqlStr = `${item.left} ${item.type.toLocaleUpperCase()} JOIN ${item.right} ON `
                    if (item.type == 'left') {
                        item.columnlist.map(c => {
                            sqlStr += `${item.left}.${c.to} = ${item.right}.${c.from} `
                        })
                    } else {
                        item.columnlist.map(c => {
                            sqlStr += `${item.left}.${c.from} = ${item.right}.${c.to} `
                        })
                    }
                    sqlStr = `<p>${sqlStr}</p>`;
                } else {
                    let leftTableName = item.left;
                    let rightTableName = item.right;
                    let type = item.type;
                    let rightTable = self.queryTableByName(item.right);
                    self.$treeContainer.find(`[data-name=${leftTableName}]>.wrap:eq(0)`).append(`
                                            <div  id="box_${rightTable.id}" class="box" data-name="${item.right}">
                                            <div class="dragable pr">
                                                <div class="info omit">${rightTable.talias}</div>
                                            </div>
                                            <div class="wrap"></div>
                                        </div>
                    `)
                    let tempSqlStr = `${item.type.toLocaleUpperCase()} JOIN ${item.right} ON `
                    if (item.type == 'left') {
                        item.columnlist.map(c => {
                            tempSqlStr += `${item.left}.${c.to} = ${item.right}.${c.from} `
                        })
                    } else {
                        item.columnlist.map(c => {
                            tempSqlStr += `${item.left}.${c.from} = ${item.right}.${c.to} `
                        })
                    }
                    sqlStr += `<p>${tempSqlStr}</p>`;
                }
            })
            this.$relationContainer.find('.content').html(sqlStr)
        } else {
            //只有一张表
            self.$treeContainer.append(`<div id="box_${this.tableList[0].id}" class="box">
                                                <div class="dragable pr">
                                                    <div class="info omit">${this.tableList[0].talias}</div>
                                                </div>
                                                <div class="wrap"></div>
                                            </div>`);
        }
        self.$relationContainer.removeClass('hide');
        self.$treeContainer.removeClass('hide')
        self.$container.find('.prompt-text').addClass('hide');
        this.updataStyle();
    }
    /**
     * 状态管理
     */
    statusMange() {
        let step = 1;
        //第一步
        if (this.getData() != false) {
            step = 2
        } else {
            return step;
        }
        //第二步
        if ($('#select-target-table').data().selectpicker.val()) {
            step = 3;
        } else {
            return step;
        }
        //第三步

        //第四步

        //第五步

    }

    resetPageElement(step) {
        if (step == 2) {
            //重置第二步
            $('#select-target-table').val('')
            $('#select-target-table').prop('disabled', 'true');
            $('#select-target-table').data().selectpicker.refresh();
            if (mappedAddView.type != 'edit') {
                //重置第三步
                $('#inputRadiosUnchecked').prop('checked', false).prop('disabled', true);//自动匹配
                mappedAddView.autoMatchFalg = false
                mappedAddView.plugins.mapped_add_list.options.data = [];
                mappedAddView.mappedCol.subList = []
                if(mappedAddView.plugins.mapped_add_list._table)
                    mappedAddView.plugins.mapped_add_list._table.fnDraw();
                //重置第四步 添加按钮
                $('#add-term-list').parent().find('.title .btn').prop('disabled', true).html('新增');
                mappedAddView.addTermData = []
                mappedAddView.addTermDataBack = []
                $('#add-term-list p').html('');
                if (mappedAddView.plugins.add_term_content._table)
                    mappedAddView.plugins.add_term_content._table.fnDraw()
                //重置第五步
                $('.step-5 select:eq(0)').val('')
                $('.step-5 select:eq(0)').prop('disabled', 'true');
                $('.step-5 select:eq(0)').data().selectpicker.refresh();
                $('.step-5 select:eq(1)').val('')
                $('.step-5 select:eq(1)').prop('disabled', 'true');
                $('.step-5 select:eq(1)').data().selectpicker.refresh();
            }
        } else if (step == 3 && mappedAddView.type != 'edit') {
            //重置第三步
            $('#inputRadiosUnchecked').prop('checked', false).prop('disabled', true);//自动匹配
            mappedAddView.autoMatchFalg = false
            mappedAddView.plugins.mapped_add_list.options.data = [];
            mappedAddView.plugins.mapped_add_list._table.fnDraw();
            //重置第四步 添加按钮
            $('#add-term-list').parent().find('.title .btn').prop('disabled', true);
            mappedAddView.plugins.add_term_content.options.data = [];
            if (mappedAddView.plugins.add_term_content._table)
                mappedAddView.plugins.add_term_content._table.fnDraw()
            $('#add-term-list p').html('');
            //重置第五步
            $('.step-5 select:eq(0)').val('')
            $('.step-5 select:eq(0)').prop('disabled', 'true');
            $('.step-5 select:eq(0)').data().selectpicker.refresh();
            $('.step-5 select:eq(1)').val('')
            $('.step-5 select:eq(1)').prop('disabled', 'true');
            $('.step-5 select:eq(1)').data().selectpicker.refresh();
        }
    }

    activatePageElement(step) {
        if (step == 2) {
            //激活第二步 
            $('#select-target-table').prop('disabled', false);
            $('#select-target-table').data().selectpicker.refresh();
        } else if (step == 3) {
            //激活第三步
            $('#inputRadiosUnchecked').prop('checked', false).prop('disabled', false);//自动匹配
            mappedAddView.autoMatchFalg = false
            //激活第四步 添加按钮
            $('#add-term-list').parent().find('.title .btn').prop('disabled', false);
            //激活第五步 
            $('.step-5 select:eq(0)').prop('disabled', false);
            $('.step-5 select:eq(0)').data().selectpicker.refresh();
            $('.step-5 select:eq(1)').prop('disabled', false);
            $('.step-5 select:eq(1)').data().selectpicker.refresh();
        }
    }
}